package com.xc.controller.protol;


import java.io.*;
import java.math.BigDecimal;
import java.util.Base64;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xc.pojo.SiteProduct;
import com.xc.service.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ag.exception.SysTipsException;
import com.ag.utils.NumberUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.xc.common.ServerResponse;
import com.xc.pojo.SiteSetting;
import com.xc.pojo.User;
import com.xc.pojo.UserStockSubscribe;
import com.xc.stock.utils.Utils;
import com.xc.utils.PropertiesUtil;

@Controller
@RequestMapping({"/api/app/user/"})
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    IUserService iUserService;

    @Autowired
    IUserPositionService iUserPositionService;
    @Autowired
    IStockService iStockService;

    @Autowired
    IFileUploadService iFileUploadService;

    @Autowired
    IUserIndexPositionService iUserIndexPositionService;

    @Autowired
    IUserFuturesPositionService iUserFuturesPositionService;

    @Autowired
    IUserStockSubscribeService iUserStockSubscribeService;
    @Autowired
    ISiteSettingService iSiteSettingService;

    @Resource
    ISiteProductService iSiteProductService;

    //添加到自选股
    @RequestMapping({"addOption.do"})
    @ResponseBody
    public ServerResponse addOption(@RequestParam("code") String code, HttpServletRequest request) {
    	User user = Utils.getCurrentUser(request);
        return this.iUserService.addOption(code, user);
    }
    
  //添加到自选股
    @RequestMapping({"addOptionBatch.do"})
    @ResponseBody
    public ServerResponse addOptionBatch(@RequestParam("codeList") String codeList, HttpServletRequest request) {
    	User user = Utils.getCurrentUser(request);
        return this.iUserService.addOptionBatch(codeList, user);
    }

    //删除自选股
    @RequestMapping({"delOption.do"})
    @ResponseBody
    public ServerResponse delOption(@RequestParam("code") String code, HttpServletRequest request) {
        return this.iUserService.delOption(code, request);
    }

    //查询是否是自选股
    @RequestMapping({"isOption.do"})
    @ResponseBody
    public ServerResponse isOption(@RequestParam("code") String code, HttpServletRequest request) {
        return this.iUserService.isOption(code, request);
    }

    //用户下单买入股票
    @RequestMapping({"buy.do"})
    @ResponseBody
    public ServerResponse buy(@RequestParam("stockId") Integer stockId, @RequestParam("buyNum") Integer buyNum, @RequestParam("buyType") Integer buyType, @RequestParam("lever") Integer lever,@RequestParam("positionType") Integer positionType, HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserPositionService.buy(stockId, buyNum, buyType, lever, positionType,request);
        } catch (Exception e) {
            log.error("用户下单操作 = {}", e);
        }
        return serverResponse;
    }

    //用户下单申购新股
    @RequestMapping({"buyNew.do"})
    @ResponseBody
    public ServerResponse buyNew(@RequestParam("stockCode") String stockCode, @RequestParam("buyNum") Integer buyNum,@RequestParam("nowPrice") Double nowPrice,   HttpServletRequest request) throws Exception {
        ServerResponse serverResponse = this.iUserPositionService.buyNew(stockCode, buyNum,nowPrice, request);
        return serverResponse;
    }
    
    @RequestMapping({"buyStockTrade.do"})
    @ResponseBody
    public ServerResponse buyStockTrade(@RequestParam("stockCode") String stockCode, @RequestParam("buyNum") Integer buyNum,@RequestParam("nowPrice") Double nowPrice,   HttpServletRequest request) throws Exception {
    	ServerResponse serverResponse = this.iUserPositionService.buyStockTrade(stockCode, buyNum,nowPrice, request);
    	return serverResponse;
    }

    //验证配售验证码
    @RequestMapping({"checkAllotment.do"})
    @ResponseBody
    public ServerResponse checkAllotment(@RequestParam("verificationCode") String verificationCode,@RequestParam("code") String code,   HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserPositionService.checkAllotment(verificationCode,code, request);
        } catch (Exception e) {
            log.error("用户下单操作 = {}", e);
        }
        return serverResponse;
    }

    //配售列表
    @RequestMapping({"allotmentList.do"})
    @ResponseBody
    public ServerResponse allotmentList( @RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserPositionService.allotmentList(pageNum,pageSize,request);
        } catch (Exception e) {
            log.error("用户下单操作 = {}", e);
        }
        return serverResponse;
    }

    @RequestMapping({"checkBlockTrade.do"})
    @ResponseBody
    public ServerResponse checkBlockTrade(@RequestParam("verificationCode") String verificationCode,@RequestParam("code") String code,   HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserPositionService.checkBlockTrade(verificationCode,code, request);
        } catch (Exception e) {
            log.error("用户下单操作 = {}", e);
        }
        return serverResponse;
    }
    
    //配售列表
    @RequestMapping({"blockTradeList.do"})
    @ResponseBody
    public ServerResponse blockTradeList( @RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,HttpServletRequest request) {
        return this.iUserPositionService.blockTradeList(pageNum,pageSize,request);
    }


    //用户平仓操作
    @RequestMapping({"sell.do"})
    @ResponseBody
    public ServerResponse sell(HttpServletRequest request, @RequestParam("positionSn") String positionSn) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserPositionService.sell(positionSn, 1);
        } catch (Exception e) {
            log.error("用户平仓操作 = {}", e);
        }
        return serverResponse;
    }

    //用户追加保证金操作
    @RequestMapping({"addmargin.do"})
    @ResponseBody
    public ServerResponse addmargin(HttpServletRequest request, @RequestParam("positionSn") String positionSn, @RequestParam("marginAdd") BigDecimal marginAdd) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserPositionService.addmargin(positionSn, 1, marginAdd);
        } catch (Exception e) {
            log.error("用户平仓操作 = {}", e);
        }
        return serverResponse;
    }

    @RequestMapping({"buyIndex.do"})
    @ResponseBody
    public ServerResponse buyIndex(@RequestParam("indexId") Integer indexId, @RequestParam("buyNum") Integer buyNum, @RequestParam("buyType") Integer buyType, @RequestParam("lever") Integer lever, HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserIndexPositionService.buyIndex(indexId, buyNum, buyType, lever, request);
        } catch (Exception e) {
            log.error("用户下单指数操作 = {}", e);
        }
        return serverResponse;
    }

    @RequestMapping({"sellIndex.do"})
    @ResponseBody
    public ServerResponse sellIndex(HttpServletRequest request, @RequestParam("positionSn") String positionSn) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserIndexPositionService.sellIndex(positionSn, 1);
        } catch (Exception e) {
            log.error("用户平仓指数操作 = {}", e);
        }
        return serverResponse;
    }

    //期货交易 用户下单
    @RequestMapping({"buyFutures.do"})
    @ResponseBody
    public ServerResponse buyFutures(@RequestParam("FuturesId") Integer FuturesId, @RequestParam("buyNum") Integer buyNum, @RequestParam("buyType") Integer buyType, @RequestParam("lever") Integer lever, HttpServletRequest request) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserFuturesPositionService.buyFutures(FuturesId, buyNum, buyType, lever, request);
        } catch (Exception e) {
            log.error("用户下单 期货 操作 = {}", e);
        }
        return serverResponse;
    }

    @RequestMapping({"sellFutures.do"})
    @ResponseBody
    public ServerResponse sellFutures(HttpServletRequest request, @RequestParam("positionSn") String positionSn) {
        ServerResponse serverResponse = null;
        try {
            serverResponse = this.iUserFuturesPositionService.sellFutures(positionSn, 1);
        } catch (Exception e) {
            log.error("用户平仓 期货 操作 = {}", e);
        }
        return serverResponse;
    }

    @Autowired
    IUserRechargeService iUserRechargeService;

    //查询 用户信息
    @RequestMapping({"getUserInfo.do"})
    @ResponseBody
    public ServerResponse getUserInfo(HttpServletRequest request) {
        return this.iUserService.getUserInfo(request);
    }

    //修改用户密码
    @RequestMapping({"updatePwd.do"})
    @ResponseBody
    public ServerResponse updatePwd(String oldPwd, String newPwd, HttpServletRequest request) {
        return this.iUserService.updatePwd(oldPwd, newPwd, request);
    }

    @RequestMapping({"findIdWithPwd.do"})
    @ResponseBody
    public ServerResponse findIdWithPwd(@RequestParam("phone") String phone){
        return this.iUserService.findIdWithPwd(phone);
    }

    @RequestMapping({"insertWithPwd.do"})
    @ResponseBody
    public ServerResponse insertWithPwd(@RequestParam("with_pwd") String with_pwd,@RequestParam("phone") String phone){
        return this.iUserService.updateWithPwd(with_pwd,phone);
    }


    @RequestMapping({"auth.do"})
    @ResponseBody
    public ServerResponse auth(String realName, String idCard,
                               @RequestParam(value = "img1Key", required = false) String img1Key,
                               @RequestParam(value = "img2Key", required = false) String img2Key,
                               @RequestParam(value = "img2Key", required = false) String img3key,
                               HttpServletRequest request) throws IOException {
        SiteProduct productSetting = iSiteProductService.getProductSetting();
        // 未开启实名认证，则不需要上传身份证图片
        if (!productSetting.getIdcardStatus()) {
            return this.iUserService.auth(realName, idCard, "", "", img3key, request);
        }

        String path = request.getSession().getServletContext().getRealPath("upload");
        String img1keyBase64 = getUploadImgBase64(img1Key, path);
        String img2keyBase64 = getUploadImgBase64(img2Key, path);
        return this.iUserService.auth(realName, idCard, img1keyBase64, img2keyBase64, img3key, request);
    }

    private String getUploadImgBase64(String imgKey, String path) throws IOException {
        if (imgKey.startsWith("/api")) {
            return "";
        }

        File file = new File(path, imgKey);
        if(!file.exists()) {
            // 文件不存在
            throw new SysTipsException("tips.msg.086");
        }

        String imgKeyBase64 = new String(Base64.getEncoder().encode(IOUtils.toByteArray(new FileInputStream(file))));
        file.delete();
        return imgKeyBase64;
    }
    
    @RequestMapping({"previewTemp.do"})
    @ResponseBody
    public void previewTemp(HttpSession session, @RequestParam(value = "path", required = false) String path, HttpServletRequest request, HttpServletResponse response) throws IOException {
		if (StringUtils.isBlank(path)) {
            // 参数非法
			throw new SysTipsException("tips.msg.098");
		}

		String uploadRoot = request.getSession().getServletContext().getRealPath("upload");
		File file = new File(uploadRoot, path);

		if (!file.exists()) {
            // 文件不存在
			throw new SysTipsException("tips.msg.086");
		}
		response.setContentType("image/png");
		OutputStream os = response.getOutputStream();
		os.write(IOUtils.toByteArray(new FileInputStream(file)));
		os.flush();
		os.close();
    }
    
    @RequestMapping({"uploadTemp.do"})
    @ResponseBody
    public ServerResponse uploadTemp(HttpSession session, @RequestParam(value = "upload_file", required = false) MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException {
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
        String fileExtentionName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String uploadFileName = UUID.randomUUID() + "." + fileExtentionName;
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.setWritable(true);
            fileDir.mkdirs();

        }
        //{  data: { path, name,identifying } }

        File tartgetFile = new File(path, uploadFileName);
        
        //{  data: { path, name,identifying } }
		file.transferTo(tartgetFile);
        JSONObject json = new JSONObject();
        json.put("path", uploadFileName);
        json.put("identifying", uploadFileName);
        json.put("name", fileName);
        
        return ServerResponse.createBySuccess(json);
    }

    //图片上传
    @RequestMapping({"upload.do"})
    @ResponseBody
    public ServerResponse upload(HttpSession session, @RequestParam(value = "upload_file", required = false) MultipartFile file, HttpServletRequest request) {
        String path = request.getSession().getServletContext().getRealPath("upload");

        ServerResponse serverResponse = this.iFileUploadService.upload(file, path);
        if (serverResponse.isSuccess()) {
            String targetFileName = serverResponse.getData().toString();
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFileName;


            Map fileMap = Maps.newHashMap();
            fileMap.put("uri", targetFileName);
            fileMap.put("url", url);

            return ServerResponse.createBySuccess(fileMap);
        }
        return serverResponse;
    }

    //资产互转
    @RequestMapping({"transAmt.do"})
    @ResponseBody
    public ServerResponse transAmt(@RequestParam("amt") Integer amt, @RequestParam("type") Integer type, HttpServletRequest request) {
        return this.iUserService.transAmt(amt, type, request);
    }

    /*新股申购-查询用户最新新股申购数据*/
    @RequestMapping({"getOneSubscribeByUserId.do"})
    @ResponseBody
    public ServerResponse getOneSubscribeByUserId(@RequestParam("userId") Integer userId, HttpServletRequest request) {
        return this.iUserStockSubscribeService.getOneSubscribeByUserId(userId, request);
    }

    /*新股申购-用户提交金额*/
    @RequestMapping({"submitSubscribe.do"})
    @ResponseBody
    public ServerResponse userSubmit(UserStockSubscribe model, HttpServletRequest request) {
        return this.iUserStockSubscribeService.userSubmit(model, request);
    }

}
